package com.espoir.shp.read04;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.WKTWriter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.shapefile.dbf.DbaseFileHeader;
import org.geotools.data.shapefile.dbf.DbaseFileReader;
import org.geotools.data.shapefile.files.ShpFiles;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.*;

public class ShapeUtils {
    /**
     * 解析.shp 点线面文件
     *
     * @param path
     * @return
     * @throws Exception
     * @author ygc
     */
    public static Map<String, String> readShapeFileData(String path) throws Exception {
        // String newPath = path.substring(0, path.lastIndexOf("."))+".dbf";
        // System.out.println(newPath);
        Map<String, String> map = new HashMap<String, String>();
        try {
            File file = new File(path);
            // File file = new File(path);
            // String fileName = file.getName();
            ShapefileDataStoreFactory sfdsf = new ShapefileDataStoreFactory();
            // 判断字符集类型
//            String encode = EncodingDetect.getEncodeType(path);
            String encode = "GBK";

            ShapefileDataStore sfds = (ShapefileDataStore) sfdsf.createDataStore(file.toURI().toURL());
            // sfds.setCharset(Charset.forName("GBK"));
            // System.out.println(encode);
            // if(encode.equals("ISO8859_1")) {
            // encode="utf8";
            // }else {
            // encode="gbk";
            // }
            // sfds.setCharset(Charset.forName("GBK"));
            sfds.setCharset(Charset.forName(encode));
            SimpleFeatureSource featureSource = sfds.getFeatureSource();

            List<AttributeDescriptor> attrList = sfds.getSchema().getAttributeDescriptors();
            JSONObject pFieldJSON = new JSONObject();
            for (AttributeDescriptor attributeDescriptor : attrList) {
                //
                String pFieldName = attributeDescriptor.getName().toString();
//                String title = DbfTitleCheck.dbfTitleCheck(pFieldName);
                String title = "test";

                String pTypeName = attributeDescriptor.getType().getBinding().getSimpleName();
                // System.out.println(attributeDescriptor.getType().getBinding().getName());
                // if (pFieldName == "the_geom") {
                if (title == "the_geom") {
                    map.put("type", pTypeName);
                    // pFieldName = "Shape";
                    title = "Shape";
                    pTypeName = "Geometry";
                }
                // logger.info(title);
                pFieldJSON.put(title, getShapeType(pTypeName));
                // pFieldJSON.put(pFieldName, getShapeType(pTypeName));

            }
            // System.out.println(pFieldJSON);
            SimpleFeatureCollection feacollection = featureSource.getFeatures();

            SimpleFeatureIterator iterator = feacollection.features();
            GeometryJSON gjson = new GeometryJSON(15);
            FeatureJSON fjson = new FeatureJSON(gjson);
            // 设置坐标参考系统编码标志控制特性。
            /**
             * 国旗坐标参考系统编码的控制特性。 当设置每个功能对象将包含一个“crs”属性描述的坐标参考系统特性。
             */
            // fjson.setEncodeFeatureCRS(true);

            // 设置标志控制特性集合坐标参考系统编码。
            fjson.setEncodeFeatureCollectionCRS(true);
            StringWriter writer = new StringWriter();
            while (iterator.hasNext()) {
                SimpleFeature sFeature = iterator.next();
                // String title=DbfTitleCheck.dbfTitleCheck(sFeature);
                //
                // Collection<Property> prop=sFeature.getProperties();
                // for(Property item: prop) {
                //
                // Name name=item.getName();
                //
                // System.out.println(name);
                // //String title=DbfTitleCheck.dbfTitleCheck(name.toString());
                //
                // }
                if (writer.toString().isEmpty()) {
                    // fjson.writeFeature(sFeature, System.out);
                    fjson.writeFeature(sFeature, writer);
                    writer.flush();
                    // logger.info(writer);
                } else {
                    writer.write(',');
                    writer.flush();
                    // fjson.writeFeature(sFeature, System.out);
                    fjson.writeFeature(sFeature, writer);
                }
            }
            String jsonData = "[" + writer.toString() + "]";
            // System.err.println(jsonData + "jsonData");

            iterator.close();
            writer.flush();
            writer.close();
            sfds.dispose();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "FeatureCollection");
            jsonObject.put("features", JSONArray.fromObject(jsonData));
            map.put("features", jsonObject.toString());
            map.put("fields", pFieldJSON.toString());

            map.put("LayerName", file.getName().replace(".shp", ""));

            map.put("op", "sucess");

            // System.out.println(map);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            map.put("op", "fail");
        }

        return map;
    }

    public static List<String> readDbfData(String path) {
        List<Map<Object, Object>> dbf = ShapeUtils.readDbfFile(path);
        for (Map<Object, Object> data : dbf) {
            for (Object k : data.keySet()) {
                System.out.println(k + " : " + data.get(k));
            }
        }
        return null;
    }

    /**
     * 解析.dbf
     *
     * @param path
     * @return
     * @throws Exception
     * @author ygc
     */
    public static List<Map<Object, Object>> readDbfFile(String path) {
        String newPath = path.substring(0, path.lastIndexOf(".")) + ".dbf";
        List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
        TreeMap<Object, Object> values = null;
//        String encode = EncodingDetect.getEncodeType(newPath);
        String encode ="GBK";

        // String code = null;
        if (encode.equals("ASCII")) {
            encode = "GBK";
        }
        if (encode.equals("ISO8859_1")) {
            encode = "UTF8";
        }
        System.out.println(encode);
        DbaseFileReader reader = null;
        try {

            reader = new DbaseFileReader(new ShpFiles(path), false, Charset.forName(encode));

            DbaseFileHeader header = reader.getHeader();

            int numFields = header.getNumFields();

            // 迭代读取记录
            while (reader.hasNext()) {

                try {
                    Object[] entry = reader.readEntry();

                    values = new TreeMap<Object, Object>();
                    for (int i = 0; i < numFields; i++) {
                        String title = header.getFieldName(i);

                        Object value = entry[i];
                        values.put(title, value);

//						String result = DbfTitleCheck.dbfTitleCheck(title);//不需要检验字段名
//						values.put(result, value);
//						System.err.println(result);
                        // System.out.println(title+"="+value);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                list.add(values);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                // 关闭
                try {
                    reader.close();
                } catch (Exception e) {
                }
            }
        }
        return list;
    }

    public static String getShapeType(String type) {
        String pDbFieldType = "";
        switch (type) {
            case "Integer":
                pDbFieldType = "INTEGER";
                break;
            case "Double":
                pDbFieldType = "DOUBLE";
                break;
            case "String":
                pDbFieldType = "VARCHAR";
                break;
            case "Date":
                pDbFieldType = "DATETIME";
                break;
            case "Boolean":
                pDbFieldType = "BOOLEAN";
                break;
            case "Geometry":
                pDbFieldType = "Geometry";
                break;
            default:
                pDbFieldType = "TEXT";
                break;
        }
        return pDbFieldType;
    }

    /**
     * 解析.shp文件数据完整版 并且转换
     *
     * @param path
     * @return
     * @throws Exception
     * @author ygc
     */
    public static List<String> parseShapeTransformPath(String path) throws Exception {
        List<String> list = new ArrayList<String>();
        Map<String, String> map = ShapeUtils.readShapeFileData(path);
        // System.out.println(map);
        String r = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(r);
        String item = jsonObject.getString("features");
        com.alibaba.fastjson.JSONObject json = JSON.parseObject(item);
        com.alibaba.fastjson.JSONArray value = json.getJSONArray("features");
        // value.contains("geometry")
        for (int i = 0; i < value.size(); i++) {
            com.alibaba.fastjson.JSONObject listValue = (com.alibaba.fastjson.JSONObject) value.get(i);
            if (listValue.containsKey("geometry")) {
                String geometry = listValue.getString("geometry");
                GeometryJSON geometryJSON2 = new GeometryJSON(15);
                org.locationtech.jts.geom.Geometry geometry2 = geometryJSON2.read(new StringReader(geometry.toString()));

                // com.alibaba.fastjson.JSONObject temp = JSON.parseObject(geometry);
                // 这里是以OGC WKT形式定义的是World Mercator投影，网页地图一般使用该投影
                final String strWKTMercator = "PROJCS[\"World_Mercator\"," + "GEOGCS[\"GCS_WGS_1984\","
                        + "DATUM[\"WGS_1984\"," + "SPHEROID[\"WGS_1984\",6378137,298.257223563]],"
                        + "PRIMEM[\"Greenwich\",0]," + "UNIT[\"Degree\",0.017453292519943295]],"
                        + "PROJECTION[\"Albers\"]," + "PARAMETER[\"false_easting\",0],"
                        + "PARAMETER[\"false_northing\",0]," + "PARAMETER[\"central_meridian\",105.0],"
                        + "PARAMETER[\"standard_parallel_1\",25.0]," + "PARAMETER[\"standard_parallel_2\",47.0],"
                        + "PARAMETER[\"latitude_of_origin\",0]," + "UNIT[\"Meter\",1]]";
                /*
                 * CoordinateReferenceSystem mercatroCRS = CRS.parseWKT(strWKTMercator);
                 * CRS.decode("EPSG:3857"); xfa1
                 */
                CoordinateReferenceSystem mercatroCRS = CRS.parseWKT(strWKTMercator);
                // 做投影转换，将WCG84坐标转换成世界墨卡托投影转
                MathTransform transform = CRS.findMathTransform(mercatroCRS, DefaultGeographicCRS.WGS84);

                org.locationtech.jts.geom.Geometry targetPoint = JTS.transform(geometry2, transform);
                StringWriter writer = new StringWriter();

                // geometryJSON2.write(targetPoint, writer);
                geometryJSON2.write(targetPoint, writer);
                // System.out.println(writer.toString());
                writer.flush();
                writer.close();
                // 返回转换以后的X和Y坐标
                // targetPoint.

                // String coordinates = temp.getString("coordinates");
                // String coordinates = temp.getString("coordinates").replace("[",
                // "").replace("]", "");
                // System.out.println(coordinates);
                list.add(writer.toString());
            } else {
                list.add(null);
            }
        }
        return list;
    }

    /**
     * 解析.shp文件数据完整版
     *
     * @param path
     * @return
     * @throws Exception
     * @author ygc
     */
    public static List<String> parseShapeData(String path) throws Exception {
        List<String> list = new ArrayList<String>();
        Map<String, String> map = ShapeUtils.readShapeFileData(path);
        System.out.println(map);
        String r = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(r);
        String item = jsonObject.getString("features");
        com.alibaba.fastjson.JSONObject json = JSON.parseObject(item);
        com.alibaba.fastjson.JSONArray value = json.getJSONArray("features");
        // value.contains("geometry")
        for (int i = 0; i < value.size(); i++) {

            com.alibaba.fastjson.JSONObject listValue = (com.alibaba.fastjson.JSONObject) value.get(i);
            if (listValue.containsKey("geometry")) {
                String geometry = listValue.getString("geometry");
                GeometryJSON geometryJSON2 = new GeometryJSON(15);


                org.locationtech.jts.geom.Geometry geometry2 = geometryJSON2.read(new StringReader(geometry.toString()));
                // com.alibaba.fastjson.JSONObject temp = JSON.parseObject(geometry);
                // 这里是以OGC WKT形式定义的是World Mercator投影，网页地图一般使用该投影
                final String strWKTMercator = "PROJCS[\"World_Mercator\"," + "GEOGCS[\"GCS_WGS_1984\","
                        + "DATUM[\"WGS_1984\"," + "SPHEROID[\"WGS_1984\",6378137,298.257223563]],"
                        + "PRIMEM[\"Greenwich\",0]," + "UNIT[\"Degree\",0.017453292519943295]],"
                        + "PROJECTION[\"Albers\"]," + "PARAMETER[\"false_easting\",0],"
                        + "PARAMETER[\"false_northing\",0]," + "PARAMETER[\"central_meridian\",105.0],"
                        + "PARAMETER[\"standard_parallel_1\",25.0]," + "PARAMETER[\"standard_parallel_2\",47.0],"
                        + "PARAMETER[\"latitude_of_origin\",0]," + "UNIT[\"Meter\",1]]";
                /*
                 * CoordinateReferenceSystem mercatroCRS = CRS.parseWKT(strWKTMercator);
                 * CRS.decode("EPSG:3857"); xfa1
                 */
                // CoordinateReferenceSystem mercatroCRS = CRS.parseWKT(strWKTMercator);
                // 做投影转换，将WCG84坐标转换成世界墨卡托投影转
                // MathTransform transform = CRS.findMathTransform(mercatroCRS,
                // DefaultGeographicCRS.WGS84);
                // Geometry targetPoint = (Geometry) JTS.transform(geometry2, transform);
                StringWriter writer = new StringWriter();

                // geometryJSON2.write(targetPoint, writer);
                geometryJSON2.write(geometry2, writer);
                writer.flush();
                writer.close();
                // 返回转换以后的X和Y坐标
                // targetPoint.

                System.out.println(writer.toString());

                // String coordinates = temp.getString("coordinates");
                // String coordinates = temp.getString("coordinates").replace("[",
                // "").replace("]", "");
                // System.out.println(coordinates);
                list.add(writer.toString());
            } else {
                list.add(null);
            }
        }
        return list;
    }

    // private static Logger logger = Logger.getLogger(ShapeUtils.class);

    // 投影转换 prj tif img 栅格数据解析
    public static void main(String[] args) throws Exception {
        // Map<String, String> map = new HashMap<String, String>();
        // String path="E:\\shape文件\\设计图斑\\设计图斑-坐标\\item.shp";
        // gbk
        // String path2 = "C:\\design_polygon\\实施方案_点措施.shp";
        // String path3 = "E:\\shape文件\\图斑\\实施方案_线措施.shp";
        String path2 = "D:\\resource\\省界原始\\省界.shp";
        // String path5="C:\\新建文件夹\\y.dbf";
        // List<String> shp = ShapeUtils.parseShapeData(path2);
        // String str="E:\\shape文件\\扰动图斑\\扰动图斑.dbf";
        // List<Map<Object, Object>> dbf=ShapeUtils.readDbfFile(str);
        // List<Map<Object, Object>> dbf=ShapeUtils.readDbfFile(str);
        // Map<String, String> map=ShapeUtils.getCoordinatesPoint(str);
        // System.out.println(map);
        List<String> list = parseShapeData(path2);
        //List<String> list=shpToWktUtil(path2);
        //System.out.println(list);
//		List<String> shp = ShapeUtils.parseShapeData(path2);
//		for (String item : shp) {
//			com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(item);
//			com.alibaba.fastjson.JSONArray value = jsonObject.getJSONArray("coordinates");
//
//			System.out.println(value);
//		}
        // Map<String, String> map1 = ShapeUtils.readShapeFileData(str);
        // String r = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
        // com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(r);
        // String item = jsonObject.getString("features");
        // com.alibaba.fastjson.JSONObject json = JSON.parseObject(item);
        // com.alibaba.fastjson.JSONArray value = json.getJSONArray("features");
        //// value.contains("geometry")
        // for (int i = 0; i < value.size(); i++) {
        // com.alibaba.fastjson.JSONObject listValue = (com.alibaba.fastjson.JSONObject)
        // value.get(i);
        // if(listValue.containsKey("geometry")){
        // String geometry = listValue.getString("geometry");
        // com.alibaba.fastjson.JSONObject coordinates = JSON.parseObject(geometry);
        //// String item2 = coordinates.getString("coordinates");
        // String item3 = coordinates.getString("coordinates").replace("[",
        // "").replace("]", "");
        //
        // String[] result=item3.split(",");
        // System.out.println(result[0]+":经度");
        // System.out.println(result[1]+":纬度");
        // map1.put("经度", result[0]);
        // map1.put("纬度", result[1]);
        //// for(String data: result) {
        //// System.out.println(data);
        //// }
        //
        // } }
    }

    /**
     * 解析获取经度纬度
     *
     * @param path
     * @return
     * @throws Exception
     * @author ygc
     */
    public static Map<String, String> getCoordinatesPoint(String path) throws Exception {
        Map<String, String> map = new LinkedHashMap<String, String>();
        Map<String, String> map1 = ShapeUtils.readShapeFileData(path);
        String r = JSON.toJSONString(map1, SerializerFeature.WriteMapNullValue);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(r);
        String item = jsonObject.getString("features");
        com.alibaba.fastjson.JSONObject json = JSON.parseObject(item);
        com.alibaba.fastjson.JSONArray value = json.getJSONArray("features");
        for (int i = 0; i < value.size(); i++) {
            com.alibaba.fastjson.JSONObject listValue = (com.alibaba.fastjson.JSONObject) value.get(i);
            if (listValue.containsKey("geometry")) {
                String geometry = listValue.getString("geometry");
                com.alibaba.fastjson.JSONObject coordinates = JSON.parseObject(geometry);
                String item3 = coordinates.getString("coordinates").replace("[", "").replace("]", "");
                String[] result = item3.split(",");
                map.put("经度", result[0]);
                map.put("纬度", result[1]);

            }

        }
        return map;
    }

    // List<Map<Object, Object>> dbf=ShapeUtils.readDbfFile(str);
    // for(Map<Object, Object> item:dbf) {
    // if(item.get("图斑编码") != null) {
    // System.out.println(item.get("图斑编码").toString());
    // }else {
    // System.out.println("图斑编码不存在");
    // }
    //
    // }

    // System.out.println(dbf);
    // String path2 ="E:\\shape文件\\验收-面\\验收准备_面措施.shp";
    // String path2="E:\\preaccept_line_path\\验收准备_线措施.shp";
    // String path4 = "E:\\shape文件\\设计图斑\\设计图斑-点状\\设计图斑-点状.shp";
    // String path1="E:\\shape文件\\设计图斑\\设计图斑-点状\\设计图斑-点状.shp";
    // String path2="E:\\shape文件\\图斑\\实施方案_点措施.shp";
    // String path2="E:\\shape文件\\图斑\\实施方案_面措施.shp";
    // String path2="E:\\shape文件\\图斑\\实施方案_面措施.shp";
    // String path2="E:\\shape文件\\图斑\\实施方案_线措施.shp";

    // try {
    // List<Map<Object, Object>> data=readDbfFile(path2);

     //List<String> shp = ShapeUtils.parseShapeTransformPath(path2);
    // for(String item:shp) {
    // System.out.println(item);
    // }
    // Map<String, String> map = ShapeUtils.readShapeFileData(path2);
    // logger.info(map);
    // logger.info(shp);
    // System.out.println(map);
    // System.out.println(shp);
    // System.out.println(shp);
    // } catch (Exception e) {
    // e.printStackTrace();
    // }

    // List<String> shp1 = ShapeUtils.parseShapeData(path2);
    // String path2 = "E:\\shape文件\\图斑\\实施方案_线措施.shp";
    // List<Map<Object, Object>> dbf=ShapeUtils.readDbfFile(path2);
    //
    // System.out.println(dbf);
    // Map<String, String> shape = ShapeUtils.readShapeFileData(path2);
    // Map<String, String> shape3 = ShapeUtils.readShapeFileData(path3);
    // Map<String, String> shape1 = ShapeUtils.readShapeFileData(path1);
    // Map<String, String> map = ShapeUtils.readShapeFileData(path2);
    // List<String> info=ShapeUtils.albersToWGS84(shp);

    // for(String item:info) {
    // System.out.println(item);
    // }

    // System.out.println(info);
    // System.out.println(shp);
    // System.out.println(shp1);
    // System.out.println(shape1);
    // System.out.println(shape3);
    // List<String> shp = ShapeUtils.parseShapeData(path2);
    // // List<Map<Object, Object>> dbf=ShapeUtils.readDbfFile(path);
    // List<String> info = ShapeUtils.albersToWGS84(shp);
    // for (String value : info) {
    // System.out.println(value);
    // }
    // List<String> shp = ShapeUtils.parseShapeData(path2);
    // for (String value : shp) {
    // System.out.println(value);
    // }
    // List<String> info=ShapeUtils.albersToWGS84(shp);
    // for (String value : info) {
    // System.out.println(value);
    // }

    // }

    // for(String value:list2) {
    // System.out.println(value);
    // }
    // String X;
    // String Y;
    //
    // for (int i = 0; i < s.length; i+=2){
    // X=s[i];
    // double[] temp=GeoUtils.albers2ll(Double.valueOf(X),0);
    //
    // }
    // for (int j = 1; j < s.length; j+=2){
    // Y=s[j];
    // double[] temp=GeoUtils.albers2ll(0,Double.valueOf(Y));
    //
    // }
    // list2.addAll(list1);

    //
    // System.out.println(s[]);
    // for(String item: s) {
    //
    //
    // }

    // List<String> Polygon=ShapeUtils.parseShapeData(path);
    // for(String value:Polygon) {
    // System.out.println(value);
    // for(Map<Object, Object> item:dbf) {
    // System.out.println(item.get("图斑编码"));
    // System.out.println(item.get("措施代码"));
    // System.out.println(item.get("措施名称"));
    // System.out.println(item.get("利用现状"));
    // System.out.println(item.get("措施数量"));
    // System.out.println(item.get("坡度"));
    // System.out.println(" ");
    // break;
    // }
    // }

    // String path="E:\\shape文件\\设计图斑\\设计图斑-点状\\设计图斑-点状.dbf";
    // List<Map<Object, Object>> list=ShapeUtils.readDbfFile(path);
    // System.out.println(list);
    // for(Map<Object, Object> item:list) {
    // // System.out.println(item.get("措施代码").toString());
    // System.out.println(item.get("措施名称").toString());
    //
    // // System.out.println(item.get("措施数量").toString());
    // }

    // }
    // /**
    // * 解析.dbf
    // *
    // * @param path
    // * @return
    // * @throws Exception
    // * @author ygc
    // */
    // public static List<Map<Object, Object>> readDbfFileValue(String path) {
    // List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
    // Map<Object, Object> values = null;
    // DbaseFileReader reader = null;
    // try {
    //
    // reader = new DbaseFileReader(new ShpFiles(path), false,
    // Charset.forName("GBK"));
    // DbaseFileHeader header = reader.getHeader();
    // int numFields = header.getNumFields();
    // // 迭代读取记录
    // while (reader.hasNext()) {
    // try {
    // Object[] entry = reader.readEntry();
    // values = new LinkedHashMap<Object, Object>();
    // for (int i = 0; i < numFields; i++) {
    // String title = header.getFieldName(i);
    // Object value = entry[i];
    //
    // values.put(title, value);
    //
    // // System.out.println(title+"="+value);
    // }
    //
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // list.add(values);
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // } finally {
    // if (reader != null) {
    // // 关闭
    // try {
    // reader.close();
    // } catch (Exception e) {
    // }
    // }
    // }
    // return list;
    // }
    // public static String GetImageExt(String strImageUrl){
    // String strExtent = "";
    // try {
    // String ImageUrl=strImageUrl.replace("\\", "\\\\");;
    // File ImageFile=new File(ImageUrl);
    // GeoTiffReader reader=new GeoTiffReader(ImageFile);
    // GridCoverage2D coverage = reader.read(null);
    // CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem2D();
    // Envelope2D coverageEnvelope = coverage.getEnvelope2D();
    // double coverageMinX = coverageEnvelope.getBounds().getMinX();
    // double coverageMaxX = coverageEnvelope.getBounds().getMaxX();
    // double coverageMinY = coverageEnvelope.getBounds().getMinY();
    // double coverageMaxY = coverageEnvelope.getBounds().getMaxY();
    //
    // } catch (Exception e) {
    // // TODO: handle exception
    // }

    /**
     * 生产建设项目，shp导入
     *
     * @param path
     * @return
     * @throws Exception
     * @author liujiao
     */
    public static List<String> parseShapeFromWeb_Mercator(String path) throws Exception {
        List<String> list = new ArrayList<String>();
        Map<String, String> map = ShapeUtils.readShapeFileData(path);
        System.out.println(map);
        String r = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(r);
        String item = jsonObject.getString("features");
        com.alibaba.fastjson.JSONObject json = JSON.parseObject(item);
        com.alibaba.fastjson.JSONArray value = json.getJSONArray("features");

        CoordinateReferenceSystem crsSRC = CRS.decode("EPSG:3857");
        // 做投影转换，将墨卡托投影转 成经纬度
        MathTransform transform = CRS.findMathTransform(crsSRC, DefaultGeographicCRS.WGS84);

        for (int i = 0; i < value.size(); i++) {
            com.alibaba.fastjson.JSONObject listValue = (com.alibaba.fastjson.JSONObject) value.get(i);
            if (listValue.containsKey("geometry")) {
                String geometry = listValue.getString("geometry");
                GeometryJSON geometryJSON2 = new GeometryJSON(15);
                org.locationtech.jts.geom.Geometry geometry2 = geometryJSON2.read(new StringReader(geometry.toString()));

                org.locationtech.jts.geom.Geometry targetPoint = (org.locationtech.jts.geom.Geometry) JTS.transform(geometry2, transform);
                StringWriter writer = new StringWriter();

                geometryJSON2.write(targetPoint, writer);
                System.out.println(writer.toString());
                writer.flush();
                writer.close();

                list.add(writer.toString());
            } else {
                list.add(null);
            }
        }
        return list;

    }
    public static List<String>  shpToWktUtil(String shpPathFile) throws IOException, TransformException {
        List<String> list=new ArrayList<String>();
        File file2 = new File(shpPathFile);
        ShapefileDataStoreFactory sfdsf = new ShapefileDataStoreFactory();
        ShapefileDataStore sfds = (ShapefileDataStore)sfdsf.createDataStore(file2.toURI().toURL());

        sfds.setCharset(Charset.forName("UTF-8"));

        SimpleFeatureSource featureSource =sfds.getFeatureSource();
//		String sourceWkt=featureSource.getInfo().getCRS().toWKT();
        SimpleFeatureCollection feacollection =featureSource.getFeatures();
        SimpleFeatureIterator iterator = feacollection.features();
        CoordinateReferenceSystem coordinateReferenceSystem=sfds.getSchema().getCoordinateReferenceSystem();

//		GeometryJSON gjson= new GeometryJSON(15);
//		FeatureJSON fjson = new FeatureJSON(gjson);
        while (iterator.hasNext()) {
            SimpleFeature sFeature = iterator.next();
            org.locationtech.jts.geom.Geometry lonlatGeo2 = (org.locationtech.jts.geom.Geometry) sFeature.getDefaultGeometry();
            org.locationtech.jts.geom.Geometry lonlatGeo= JTS.toGeographic(lonlatGeo2, coordinateReferenceSystem) ;

//            修改
            Geometry lonlatGeo3 = (Geometry) sFeature.getDefaultGeometry();
            if (lonlatGeo == null) {
                continue;
            }

            WKTWriter wktWriter = new WKTWriter();
            StringWriter stringWriter2 = new StringWriter();
            wktWriter.write(lonlatGeo3, stringWriter2);
            String wktStr = stringWriter2.toString();
            stringWriter2.close();
            stringWriter2 = null;

//			System.out.println(wktStr);
            list.add(wktStr);
//			StringWriter stringWriter = new StringWriter();
//			fjson.writeFeature(sFeature, stringWriter);
//			String geoJson = stringWriter.toString();
//			stringWriter.close();
//			stringWriter = null;
//			JSONObject jsonObject = JSONObject.parseObject(geoJson);
//			String lowAttr = jsonObject.getJSONObject("properties").toJSONString();
//			System.out.println(wktStr);
        }
        return list;

    }
}
